﻿Imports Entities
Imports DataAccess
Public Class VentaBL
    Public Shared Function Save(ByVal zObject As VENTAS, ByVal zList As List(Of DETALLEVENTA), ByVal zGaraPendiente As Boolean, ByVal zGarantiaCambiada As GarantiasCambiadas) As VENTAS
        Try
            Dim venta = VentaDAL.Create(zObject)
            If IsNothing(venta) Then
                Return Nothing
            End If
            If zGarantiaCambiada.GarantiaCambiadaId > 0 Then
                zGarantiaCambiada.Venta = venta.VENTA
                zGarantiaCambiada.Cliente = venta.CLIENTE
                GarantiasCambiadasDAL.Create(zGarantiaCambiada)
            End If
            Dim listFinal As New List(Of DETALLEVENTA)

            Dim itemList = ItemBL.List
            For Each item In itemList
                Dim det As New DETALLEVENTA
                For Each rec In zList
                    If item.ITEM = rec.ITEM Then
                        If IsNothing(det.CANTIDAD) Then det = rec Else det.CANTIDAD += 1
                    End If
                Next
                If Not IsNothing(det.CANTIDAD) Then listFinal.Add(det)
            Next

            Dim garaList = GarantiaBL.List
            For Each garantia In garaList
                Dim det As New DETALLEVENTA
                For Each rec In zList

                    If garantia.GARANTIA = rec.GARANTIA Then
                        If IsNothing(det.CANTIDAD) Then det = rec Else det.CANTIDAD += 1
                    End If
                Next
                If Not IsNothing(det.CANTIDAD) Then listFinal.Add(det)
            Next
            For Each rec In listFinal
                rec.VENTA = venta.VENTA
                DetalleVentaDAL.Create(rec)
                ItemBL.UpdateStockVenta(rec.ITEM, rec.PRECIOVENTA)
                If zGaraPendiente Then
                    GarantiaBL.UpdateStock(ItemBL.GetGarantia(rec.ITEM), 1, rec.PRECIOVENTA)
                End If
                GarantiaBL.UpdateStock(rec.GARANTIA, 1, rec.PRECIOVENTA)
            Next
            Return venta
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Public Shared Function Update(ByVal zVenta As ventas) As ventas
        Return VentaDAL.Update(zVenta)
    End Function

    Public Shared Function UpdateDevuelto(ByVal zVentaId As Long) As VENTAS
        Return VentaDAL.UpdateDevuelto(zVentaId)
    End Function

    Public Shared Function ListByPedidoPOSId() As List(Of VentasPOS)
        Dim lista As New List(Of VENTAS)
        Dim listaF As New List(Of VentasPOS)
        lista = VentaDAL.ListByPedidoPOSId
        If IsNothing(lista) Then Return Nothing
        For Each rec In lista
            Dim boleta = BoletaBL.SearchById(rec.BOLETA)
            Dim ven As New VentasPOS
            With ven
                .VentaId = rec.VENTA
                .Fecha = CDate(rec.FECHA).ToShortDateString
                .Hora = CDate(rec.FECHA).ToShortTimeString
                .PedidoPOSId = rec.PedidoPOSId
                .ValorDescuento = boleta.DESCUENTO
            End With
            listaF.Add(ven)
        Next
        Return listaF
    End Function

    Public Shared Function UpdateDetalles(ByVal zVentaId As Long, ByVal zDetallesList As List(Of DetalleVentaR)) As Boolean
        Dim oldDetList = GetDetalleR(zVentaId)
        'SUMAR EL DETALLE ANTIGUO AL STOCK
        For Each oldDet In oldDetList
            If oldDet.ItemId > 0 Then
                ItemBL.UpdateStockMasivo(oldDet.ItemId, oldDet.Cantidad)
            End If
            If oldDet.GarantiaId > 0 Then
                GarantiaBL.UpdateStockMasivo(oldDet.GarantiaId, oldDet.Cantidad)
            End If
        Next
        'ELIMINAR EL DETALLE ANTERIOR
        DetalleVentaDAL.DeleteDetalle(zVentaId)
        'RESTAR EL STOCK DEL NUEVO DETALLE
        For Each newDetR In zDetallesList
            Dim newDet As New detalleventa
            With newDet
                .VENTA = zVentaId
                .GARANTIA = newDetR.GarantiaId
                .ITEM = newDetR.ItemId
                .PRECIOVENTA = newDetR.Valor
                .CANTIDAD = newDetR.Cantidad
            End With
            'GUARDAR EL NUEVO DETALLE
            DetalleVentaDAL.Create(newDet)
            If newDetR.ItemId > 0 Then
                ItemBL.UpdateStockMasivo(newDetR.ItemId, -newDetR.Cantidad)
            End If
            If newDetR.GarantiaId > 0 Then
                GarantiaBL.UpdateStockMasivo(newDetR.GarantiaId, -newDetR.Cantidad)
            End If
        Next
        Return True
    End Function

    Public Shared Function List() As List(Of VENTAS)
        Dim lista As New List(Of VENTAS)
        lista = VentaDAL.List

        If lista.Count > 0 Then
            Return lista
        Else
            Return Nothing
        End If
    End Function

    Public Shared Function ListByFechas(ByVal zFechaDesde As Date, ByVal zFechaHasta As Date) As List(Of VentaR)
        Dim ventasList As New List(Of VENTAS)
        ventasList = VentaDAL.ListByFechas(zFechaDesde, zFechaHasta)
        Return ListVentaToListVentaR(ventasList)
    End Function

    Public Shared Function SavePagosVenta(ByVal zobject As pagosventa) As pagosventa
        Return PagosVentaDAL.Create(zobject)
    End Function

    Private Shared Function ListVentaToListVentaR(ByVal list As List(Of VENTAS)) As List(Of VentaR)

        Dim listaR As New List(Of VentaR)
        If IsNothing(list) Then Return Nothing
        For Each venta In list
            Dim cliente = ClienteBL.SearchById(venta.CLIENTE)
            Dim calle = CalleBL.SearchById(cliente.CALLE)
            Dim boleta = BoletaBL.SearchById(venta.BOLETA)

            Dim pagolist As New List(Of PAGOS)
            pagolist = PagosBL.ListByVentaId(venta.VENTA)
            Dim formaPago As String = ""
            Dim montoPagado As Long = 0
            If Not IsNothing(pagolist) AndAlso pagolist.Count > 0 Then
                formaPago = FormaPagoBL.GetDescripcion(pagolist(0).FORMAPAGO)
                For Each pago In pagolist
                    montoPagado += pago.MONTO
                Next
            End If
            If IsNothing(venta.PENDIENTE) Then venta.PENDIENTE = 0
            If montoPagado < 0 Then montoPagado = 0
            Dim venR As New VentaR
            With venR
                .Kilos = venta.KILOS
                .VentaId = venta.VENTA
                .Numero = cliente.NUMERO
                .Calle = calle.NOMBRE
                .Villa = VillaBL.GetNombre(calle.VILLA)
                .Hora = CDate(venta.FECHA).ToShortTimeString
                .FormaPago = formaPago
                .SubTotal = FormatCurrency(venta.SUBTOTAL)
                .Descuentos = FormatCurrency(venta.DESCTO + venta.DESCTOPOS)
                .Total = FormatCurrency(venta.PRECIOTOTAL)
                .Pagado = FormatCurrency(montoPagado)
                .Pendiente = FormatCurrency(venta.PENDIENTE)
                .DetalleVenta = VentaBL.GetDetalleR(venta.VENTA)
            End With
            listaR.Add(venR)
        Next

        If listaR.Count > 0 Then
            Return listaR
        Else
            Return Nothing
        End If
    End Function

    Public Shared Function ListCierreDiarioP(ByVal zFecha As Date, ByVal zCamion As String, ByVal zChofer As String) As List(Of VentaR)
        Dim ventasList As New List(Of VENTAS)
        ventasList = VentaDAL.ListToCierreDiario(zFecha, zCamion, zChofer)
        Dim listaR As New List(Of VentaR)
        If IsNothing(ventasList) Then Return Nothing
        Return ListVentaToListVentaR(ventasList)
    End Function

    Public Shared Function ListGeneral(ByVal zFechaDesde As Date, ByVal zFechaHasta As Date) As List(Of VentaLG)
        Dim ventasList As New List(Of VENTAS)
        Dim ventasRList As New List(Of VentaR)
        Dim listaF As New List(Of VentaLG)

        ventasList = VentaDAL.ListByFechas(zFechaDesde, zFechaHasta)
        ventasRList = ListVentaToListVentaR(ventasList)
        If Not IsNothing(ventasRList) Then
            For Each venR In ventasRList
                listaF.Add(VentarToVetaLG(venR))
            Next
        End If
        If listaF.Count > 0 Then
            Return listaF
        Else
            Return Nothing
        End If
    End Function

    Private Shared Function VentarToVetaLG(ByVal venta As VentaR) As VentaLG
        Dim pagosList = PagosBL.ListByVentaId(venta.VentaId)
        Dim vent = VentaBL.SearchById(venta.VentaId)
        Dim pagoslistR As New List(Of PagoR)
        If Not IsNothing(pagosList) AndAlso pagosList.Count > 0 Then
            pagoslistR = PagosBL.ListPagosToLIstPgosR(pagosList)
        End If
        Dim venLG As New VentaLG
        With venLG
            .Numero = venta.Numero
            .Calle = venta.Calle
            .DetalleVenta = venta.DetalleVenta
            .Hora = venta.Hora
            .SubTotal = venta.SubTotal
            .Descuentos = venta.Descuentos
            .Pagado = venta.Pagado
            .Pendiente = venta.Pendiente
            .Total = venta.Total
            .Villa = venta.Villa
            .VentaId = venta.VentaId

            .Kilos = venta.Kilos
            .Chofer = ChoferBL.GetNombre(vent.RUT)
            .Camion = CamionBL.GetDescripcion(vent.PATENTE).Trim
            .Fecha = CDate(vent.FECHA).ToShortDateString
            .Pagos = pagoslistR
        End With
        Return venLG
    End Function

    Public Shared Function ListBalonPendientes() As List(Of ClienteBalonPendiente)
        Dim lista As New List(Of VENTAS)

        Dim listaF As New List(Of ClienteBalonPendiente)
        lista = VentaDAL.ListBalonPendientes

        For Each venta In lista
            Dim obj As New ClienteBalonPendiente
            Dim cli As New CLIENTES
            Dim calle As New CALLES

            cli = ClienteBL.SearchById(venta.CLIENTE)
            calle = CalleBL.SearchById(cli.CALLE)

            With obj
                .VentaId = venta.VENTA
                .ClienteId = cli.CLIENTE
                .Calle = calle.NOMBRE
                .Fono = cli.FONO
                .Nombre = cli.NOMBRE
                .Numero = cli.NUMERO
                .Rut = cli.RUT
                .Villa = VillaBL.GetNombre(calle.VILLA)

                .GarantiaId = venta.GARANTIA
                .Descripcion = GetDetalleDescripcion(venta.VENTA)
                .FechaDevolucion = cli.FECHADEVOLUCION
                .FechaVenta = CDate(venta.FECHA).ToShortDateString
                .HoraVenta = CDate(venta.FECHA).ToShortTimeString
                .Garantia = GarantiaBL.GetDescripcion(venta.GARANTIA)
            End With
            listaF.Add(obj)
        Next

        If listaF.Count > 0 Then
            Return listaF
        Else
            Return Nothing
        End If
    End Function

    Public Shared Function UpdateGarantiaPendiente(ByVal zId As Long) As Boolean
        Return VentaDAL.UpdateGarantiaPendiente(zId)
    End Function

    Public Shared Function SearchById(ByVal zId As Long) As VENTAS
        Dim bol As New VENTAS
        bol = VentaDAL.SearchById(zId)
        Return bol
    End Function

    Public Shared Function SearchByBoletaId(ByVal zId As Long) As VENTAS
        Dim bol As New VENTAS
        bol = VentaDAL.SearchByBoletaId(zId)
        Return bol
    End Function

    Public Shared Function GetDetalleR(ByVal zVentaId As Long) As List(Of DetalleVentaR)
        Dim lista = DetalleVentaDAL.ListByVentaIdId(zVentaId)
        Dim listaR As New List(Of DetalleVentaR)
        For Each rec In lista
            Dim venR As New DetalleVentaR
            With venR
                .ItemId = rec.ITEM
                .GarantiaId = rec.GARANTIA
                If rec.ITEM > 0 Then .Descripcion = ItemBL.GetDescripcion(rec.ITEM)
                If rec.GARANTIA > 0 Then .Descripcion = GarantiaBL.GetDescripcion(rec.GARANTIA)
                '.PrecioVenta = rec.PRECIOVENTA
                .Valor = rec.PRECIOVENTA
                .Cantidad = rec.CANTIDAD
            End With
            listaR.Add(venR)
        Next
        Return listaR
    End Function

    Public Shared Function GetDetalleDescripcion(ByVal zVentaId As Long) As String
        Dim lista = DetalleVentaDAL.ListByVentaIdId(zVentaId)
        Dim desc As String = ""
        For Each rec In lista
            If rec.ITEM > 0 Then
                desc = (ItemBL.GetDescripcion(rec.ITEM))
            End If
        Next
        Return desc
    End Function

    Public Shared Function ListPendientes() As List(Of VentasPendientesR)
        Dim ventasList As New List(Of ventas)
        Dim ListaF As New List(Of VentasPendientesR)
        Dim fpagosList = FormaPagoBL.List
        ventasList = VentaDAL.ListPendientes


        For Each venta In ventasList
            'Dim boleta = BoletaDAL.SearchByPagoId(pago.PAGO)

            Dim cliente = ClienteBL.SearchByIdALL(venta.CLIENTE)
            Dim cliP = ClienteBL.ClientesToClientesP(cliente)

            Dim ventaPR As New VentasPendientesR
            Dim detalle = DetalleVentaDAL.ListByVentaIdId(venta.VENTA)
            With ventaPR
                .ClienteId = cliP.ClienteId
                .BoletaId = venta.BOLETA
                .VentaId = venta.VENTA
                .Numero = cliP.Numero
                .Calle = cliP.Calle
                .Villa = cliP.Villa
                .Rut = cliP.Rut
                .Nombre = cliP.Nombre
                .Fono = cliP.Fono
                .FechaVenta = CDate(venta.FECHA).ToShortDateString
                .HoraVenta = CDate(venta.FECHA).ToShortTimeString
                If IsNothing(venta.FECHAPAGO) Then .FechaPago = "" Else .FechaPago = venta.FECHAPAGO
                .MontoTotal = venta.PRECIOTOTAL
                .MontoPendiente = venta.PENDIENTE

                For Each ven In detalle
                    If Not IsNothing(.Producto) AndAlso .Producto.Length > 0 Then .Producto += ", "
                    If ven.ITEM > 0 Then
                        .Producto += ItemBL.GetDescripcion(ven.ITEM)
                    End If
                    If ven.GARANTIA > 0 Then
                        .Producto += GarantiaBL.GetDescripcion(ven.GARANTIA)
                    End If
                Next
            End With
            ListaF.Add(ventaPR)
        Next
        If ListaF.Count > 0 Then
            Return ListaF
        Else
            Return (Nothing)
        End If
    End Function

    Public Shared Function Delete(ByVal zVentaId As Long) As Boolean
        Dim detList = DetalleVentaDAL.ListByVentaIdId(zVentaId)
        For Each det In detList
            If det.ITEM > 0 Then
                ItemBL.UpdateStockMasivo(det.ITEM, det.CANTIDAD)
            End If
            If det.GARANTIA > 0 Then
                GarantiaBL.UpdateStockMasivo(det.GARANTIA, det.CANTIDAD)
            End If
        Next
        'DetalleVentaDAL.DeleteDetalle(zVentaId)

        Dim pagosList = PagosBL.ListByVentaId(zVentaId)
        For Each pag In pagosList
            PagosDAL.Delete(pag)
        Next

        Return VentaDAL.Delete(zVentaId)
    End Function

    Public Shared Function RecibirPendiente(ByVal zVentaId As Long, ByVal zPago As pagos) As ventas
        Dim venta = SearchById(zVentaId)
        venta.PENDIENTE = venta.PENDIENTE - zPago.MONTO
        Dim bolPago As New pagosventa
        bolPago.VENTA = venta.VENTA
        bolPago.Pago = zPago.PAGO
        venta = Update(venta)
        SavePagosVenta(bolPago)
        Return venta
    End Function
End Class
